/*----------------------------------------------------------------
FUNCTIONS---------------------------------------------/*
/*to post the seleted file*/

function ContinueClick() {
    init_mapping();
    document.getElementById("UploadFile").click();
}

function init_review_import() {
    $.fancybox($('#popup-processing-reviewimport'), {
        padding: 0,
        closeBtn: false,
        helpers: {
            overlay: {
                opacity: 0.8,
                css: { 'background-color': '#11619d' },
                closeClick: false
            }
        }
    });
}

function ChangeViewType(vt) {
    MappingModel.ViewType = vt;
    if (MappingModel.Initialized) {
        MappingModel.UpdateView();
    }
}

//Edit cell
function Keypress_Event(evt, value, id) {
    var charCode = (evt.which) ? evt.which : evt.keyCode

    if (charCode == 13 || charCode == 9) {
        Update_Cell(value, id);

        var scrollleft = $("#gridview").scrollLeft();


        if (scrollleft > 0) {
            $('#scrollbar').css("display", "none");
        }
    }

    return true;
}

//Validation cell
function Update_Cell(value, id) {
    var _arrayId = id.split('-');
    var _row = _arrayId[1];
    var _cell = _arrayId[0];
    var _ArrayErrorRows = ReviewImportModel.ErrorRows();
    var _ArrayValidation = ReviewImportModel.ColumnHeaders()[_cell].RegularExpressions;
    var _IsRequired = ReviewImportModel.ColumnHeaders()[_cell].IsRequired;
    var _check = false;
    value = $.trim(value);



    if (_IsRequired) {
        if (value != "") {
            if (_ArrayValidation != null && _ArrayValidation != "") {
                if (CheckValidation(value, _ArrayValidation)) {
                    _check = true;

                }

            }
            else {
                _check = true;
            }
        }
        else {
            _check = false;
        }
    }
    else {
        if (value != "") {
            if (_ArrayValidation != null && _ArrayValidation != "") {
                if (CheckValidation(value, _ArrayValidation)) {

                    _check = true;

                }
            }
            else {
                _check = true;
            }
        }
        else {
            _check = true;
        }
    }


    if (_check) {
        _ArrayErrorRows[_row].Cells[_cell].Value = value;
        _ArrayErrorRows[_row].Cells[_cell].IsDone = true;
        _ArrayErrorRows[_row].Cells[_cell].IsError = false;
        _ArrayErrorRows[_row].Cells[_cell].ClassName = "col1 done";
        ReviewImportModel.ErrorRows(_ArrayErrorRows);
        $('#' + id).parent().removeClass('error').addClass('done');
        $('#' + id).replaceWith("<span class='w' id='" + id + "' textintable ellipsis' style='min-height: 21px;'>" + _ArrayErrorRows[_row].Cells[_cell].Value + "</span>");
        $('#' + id).parent().find('.anchor').hide();

    }
    else {
        _ArrayErrorRows[_row].Cells[_cell].Value = value;
        _ArrayErrorRows[_row].Cells[_cell].IsDone = false;
        _ArrayErrorRows[_row].Cells[_cell].IsError = true;
        _ArrayErrorRows[_row].Cells[_cell].ClassName = "col1 error";
        $('#' + id).attr('disabled', 'disabled');
        $('#' + id).parent().removeClass('done').addClass('error');
        $('#' + id).parent().find('.anchor').show();
        $('#' + id).parent().find('.anchor .btn.btn-downarrow').show();
        ReviewImportModel.ErrorRows(_ArrayErrorRows);
    }
}

//Check validation
function CheckValidation(value, pattern) {
    var regExp = new RegExp(pattern, "");
    return regExp.test(value);
}
function init_send_data_to_server() {
    $.fancybox($('#popup-processing-senddata'), {
        padding: 0,
        closeBtn: false,
        helpers: {
            overlay:
			{
			    opacity: 0.8,
			    css: { 'background-color': '#11619d' },
			    closeClick: false
			}
        }
    });
}
function updateLeadStatus() {
    var strLeadStatus = !UploadFileModel.classLead();
    var data = { "LeadStatus": strLeadStatus };
    $.post("/LeadCall/UpdateLeadStatus", data, function (LeadStatus) {
        UploadFileModel.classLead(LeadStatus);
        HelpModel.classLead(LeadStatus);
        MappingModel.classLead(LeadStatus);
        ReviewImportModel.classLead(LeadStatus);
    });

}
function updateCallStatus() {
    var strCallStatus = !UploadFileModel.classCall();
    var data = { "CallStatus": strCallStatus };
    $.post("/LeadCall/UpdateCallStatus", data, function (CallStatus) {
        UploadFileModel.classCall(CallStatus);
        HelpModel.classCall(CallStatus);
        MappingModel.classCall(CallStatus);
        ReviewImportModel.classCall(CallStatus);
    });
}


function hscroll_size() 
{
    setTimeout(function () {

        var coulums = $("#gridview > div.title div.col1").length;
        if (coulums > 40)
            var tblWidth = $("#gridview > div.title div.col1").length * 141 + 40;
        else
            var tblWidth = $("#gridview > div.title div.col1").length * 141 + 20;

        if (coulums < 6) {
            $("#gridview").css("overflow", "hidden");
        }
        else {
            $("#gridview").css("overflow", "auto");

        }
        $("#gridview > div > div.line,#gridview > div.title, #gridview > div:has(div.line)").css("minWidth", tblWidth);

        $("div#gridview, div#gridview > div.title, div#gridview > div > div.line").width("");

        var newWidth = $("div#panelReview").width() - 352;
        $("div#gridview").width(newWidth);
    },500);
}

//to set width for grid and handle for scrolling
$(document).ready(function () {
    var widthfull = $('#panelReview').width();
    $('#gridview').width("");
    $('#gridview').css("width", widthfull - 385);

    var currentSearchText = $('#searchKeywordstep2').val();
    var textDefault = "Search Header Names";

    $('#searchKeywordstep2').focus(function () {
        currentSearchText = $('#searchKeywordstep2').val();
        if ($(this).val() == textDefault) {
            $(this).val("");
        }
    });

    

    $('#searchKeywordstep2').blur(function () {
        if ((($(this).val() == null) || ($(this).val() == '')) && (currentSearchText == textDefault)) {
            $(this).val(textDefault);
        }
    });

    $('#gridview').scroll(function () {

        var scrollleft = $("#gridview").scrollLeft();


        if (scrollleft > 0) {
            $('#scrollbar').css("display", "none");

        }
        else if (ReviewImportModel.CountErrorG2() > 0) {
            $('#scrollbar').css("display", "block");
        }

    });

});


$(window).resize(function () 
{
    hscroll_size();
});


/*to use for dragging and dropping*/
ko.bindingHandlers.itemDrag =
{
    init: function (element) {
        $(element).draggable({
            revert: "invalid",
            containment: '#wrapper',
            appendTo: 'body',
            helper: 'clone'
        });
    }
}

ko.bindingHandlers.itemDrop =
{
    init: function (element) {
        $(element).droppable({
            accept: ".i-matched1",
            drop: function (event, ui) {
                var DragDataId = ui.draggable.find(".IdField").val();
                var DragFieldName = ui.draggable.find(".FieldName").text();
                MappingModel.MatchColumn(DragDataId, DragFieldName);
                MappingModel.SearchFieldText("Search Header Names");
                MappingModel.UpdateView();
                ui.draggable.remove();
                $('.match-header').css("overflow", "auto");
                $('.panel').css("overflow", "auto");
                if (($("#searchKeywordstep2").is(":focus")) && ($('#searchKeywordstep2').val() == "Search Header Names")) {
                    $('#searchKeywordstep2').val("");
                }
            }
        });
    }
}

ko.bindingHandlers.itemDropBack =
{
    init: function (element) {
        $(element).droppable({
            accept: ".i-matched",
            drop: function (event, ui) {
                var HeaderName = ui.draggable.parent().find(".lb").text();
                MappingModel.UnMatchColumn(HeaderName, false);
                MappingModel.SearchFieldText("Search Header Names");
                MappingModel.UpdateView();
                ui.draggable.remove();
                $('.match-header').css("overflow", "auto");
                $('.panel').css("overflow", "auto");
                if (($("#searchKeywordstep2").is(":focus")) && ($('#searchKeywordstep2').val() == "Search Header Names")) {
                    $('#searchKeywordstep2').val("");
                }
            }
        });
    }
}
ko.bindingHandlers.itemDragBack =
{
    init: function (element) {
        $(element).draggable({
            revert: 'invalid',
            containment: '#wrapper',
            start: function () {
                $('#matchrightside').css("z-index", "1000");
                $('.match-header').css("overflow", "visible");
                $('.panel').css("overflow", "visible");
                $('#matchrightside .i-matched').css("z-index", "100");
                $('#matchrightside .i-matched1').css("z-index", "100");
            },
            appendTo: '#matchrightside',
            helper: 'clone'
        });
    }
}

ko.bindingHandlers.griddropdown =
{
    init: function (element) {
        $(element).click(function () {
            //get id of cell+type
            var id = $(element).attr("id");
            var _arrayId = id.split('+');
            //get type
            var type = _arrayId[1];
            //get id of cell
            var idofcell = _arrayId[0];
            //set id for options
            var idofedit = idofcell + "+Edit";
            var idofcancel = idofcell + "+Cancel";
            var idofignore = idofcell + "+Ignore";
            var idofignoreall = idofcell + "+Ignoreall";

            if (type != 64)
                $(element).parent().parent().append("<span class='moreoptions'><a href='javascript:void(1);' id = '" + idofedit + "' onClick='EditCell(id);'>Edit</a><a href='javascript:void(1);' id='" + idofcancel + "' onClick='Cancel(id);'>Clear Contents</a></span>");
            else
                $(element).parent().parent().append("<span class='moreoptions'><a href='javascript:void(1);' id = '" + idofedit + "' onClick='EditCell(id);'>Edit </a><a href='javascript:void(1);' id = '" + idofcancel + "' onClick='Cancel(id);'>Clear Contents</a><a href='javascript:void(1);' id = '" + idofignore + "' onClick='IgnoreValidation(id);'>Ignore </a><a href='javascript:void(1);' id = '" + idofignoreall + "' onClick='IgnoreAllValidation(id)'>Ignore All</a></span>");

            $('#' + idofcell).parent().find('.moreoptions').show();
        });
    }
}


ko.applyBindings(UploadFileModel, document.getElementById("ImportLeadFirstStep"));
ko.applyBindings(HelpModel, document.getElementById("ImportLeadHelp"));
ko.applyBindings(MappingModel, document.getElementById("ImportLeadSecondStep"));
ko.applyBindings(ReviewImportModel, document.getElementById("ImportLeadThirdStep"));